<template>
  <SvgIcon
    v-if="isSvgIcon"
    :size="size"
    :name="getSvgIcon"
    :class="[$attrs.class, 'anticon']"
    :spin="spin"
  />

  <span
    v-else
    ref="elRef"
    :class="[$attrs.class, 'app-iconify anticon', spin && 'app-iconify-spin']"
    :style="getWrapStyle"
  ></span>
</template>

<script setup>
import SvgIcon from "@/components/Icon/src/SvgIcon.vue";
import Iconify from "@purge-icons/generated";
import { isString } from "@/utils/is";
import { computed, watch, unref, onMounted, ref, nextTick } from "vue";

const SVG_END_WITH_FLAG = "|svg";

defineOptions({ name: "Icon" });

const props = defineProps({
  icon: {
    type: String,
    default: "",
  },
  color: {
    type: String,
    default: "",
  },
  size: {
    type: [String, Number],
    default: "1em",
  },
  spin: {
    type: Boolean,
    default: false,
  },
  prefix: {
    type: Boolean,
    default: false,
  },
});

const elRef = ref(null);

const isSvgIcon = computed(() => props.icon.endsWith(SVG_END_WITH_FLAG));
const getSvgIcon = computed(() => props.icon.replace(SVG_END_WITH_FLAG, ""));
const getIconRef = computed(
  () => `${props.prefix ? props.prefix + ":" : ""}${props.icon}`
);

const update = async () => {
  if (unref(isSvgIcon)) return;

  const el = unref(elRef);
  console.assert(el);

  if (!el) return;
  await nextTick();
  const icon = unref(getIconRef);
  if (!icon) return;

  const svg = Iconify.renderSVG(icon, {});
  if (svg) {
    el.textContent = "";
    el.appendChild(svg);
  } else {
    console.log(2);
    const span = document.createElement("span");
    span.className = "iconify";
    span.dataset.icon = icon;
    el.textContent = "";
    el.appendChild(span);
  }
};

const getWrapStyle = computed(() => {
  const { size, color } = props;
  let fs = size;
  if (isString(size)) {
    fs = parseInt(size, 10);
  }

  return {
    fontSize: `${fs}px`,
    color: color,
    display: "inline-flex",
  };
});

// icon变更 被监听到 在视图更新后 更新dom
watch(() => props.icon, update, { flush: "post" });

onMounted(update);
</script>

<style lang="scss" scoped></style>
